import React, {useEffect,useState} from 'react';
import { Form, Button, DatePicker,TreeSelect,Table,Input, Modal,Row, Col,Select} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import {vacationType} from "@/utils/constant";
import {getReportBackFrequency} from '../service';

const FormItem = Form.Item;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const HolidayAddForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser,record,title} = props;
  const [form] = Form.useForm();
  const [data,setData] = useState([]);
  const [temp,setTemp] = useState({});

  const columns = [
    {
      title: '请假/调休天数',
      dataIndex: 'dayNum',
      hideInSearch: true,
      render:(text) => {
        return text !== '-' ? text + "天" : '';
      }
    },
    {
      title: '请假类型',
      dataIndex: 'type',
      hideInSearch: true,
      render: (text) => {
        const res = vacationType.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '假期开始日期',
      dataIndex: 'beginGmtDate',
      hideInSearch: true,
      render: (text) => {
        return moment(text).format('YYYY-MM-DD HH:mm');
      },
    },
    {
      title: '假期结束日期',
      dataIndex: 'endGmtDate',
      hideInSearch: true,
      render: (text) => {
        return moment(text).format('YYYY-MM-DD HH:mm');
      },
    }
  ];

  useEffect(() => {
    if(currentUser){
      if(visible){
        getReportBackFrequency(currentUser.id).then(res => {
          let temp = [];
          res?.frequencyList.map((item,index) => {
            temp.push({...item, key:index});
          });
          setData(temp);
        });
      }
      if(record && visible){
        form.setFieldsValue({...record,leaveDate:[moment(record.beginGmtCancel),moment(record.endGmtCancel)]});
      }else{
        form.setFieldsValue({code:currentUser.usercode,userName:currentUser.name,orgName:currentUser.orgname,
          unitName:currentUser.department,jobName:currentUser.jobname,jobLevel:currentUser.jobLevel
        });
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    setTemp({});
    setData([]);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
      beginGmtCancel:moment(fieldsValue.leaveDate[0]).format('YYYY-MM-DD') + " 00:00:00",
      endGmtCancel:moment(fieldsValue.leaveDate[1]).format('YYYY-MM-DD') + " 00:00:00",
      id:record && record.id
    });
  };

  const computeDay = () =>{
    const fieldsValue = form.getFieldValue();
    console.log("调东软接口，获取请假时长！");
  };

  const rowSelection = {
    selectedRowKeys:[0],
    onChange: (selectedRowKeys, selectedRows) => {
      setTemp(selectedRows);
    },
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="code" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="userName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgName" label="公司" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitName" label="部门" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobName" label="岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevel" label="职级">
              <Select disabled={true} />
            </FormItem>
          </Col>
          <Col span={24} style={{marginBottom:'24px'}}>
            <Table rowSelection={{type: 'radio',...rowSelection}} dataSource={data} columns={columns} pagination={false}/>
          </Col>
          <Col {...colStyle}>
            <FormItem name="leaveDate" label="销假起止日期" rules={[{required: true, message: '销假起止日期不能为空'}]}>
              <RangePicker className='widthStyle' onChange={computeDay}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="longCancel" label="销假时长" rules={[{required: true, message: '销假时长不能为空'}]} extra={"缺东软接口"}>
              <Input placeholder='最小单位半天' suffix="天"/>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="remarkCancel" labelCol={{span: 2}} label="销假说明" rules={[{required: true, message: '销假说明不能为空'}]}>
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      centered
      title={`销假`+title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({user}) => ({currentUser: user.currentUser}))(HolidayAddForm);
